package com.example.controller;

import com.example.dao.TSongMapper;
import com.example.entity.TSongEntity;
import com.example.service.TSongService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Date;
import java.util.UUID;

@RestController
public class FileUpload {

    @Autowired
    TSongMapper tSongMapper;

    @RequestMapping("/file")
    public String upload(@RequestParam(value = "file") MultipartFile file){
        String originalFilename = file.getOriginalFilename();
        String[] attribute = originalFilename.split("\\.")[0].split("-");
        String fileName = UUID.randomUUID().toString()+"."+originalFilename.split("\\.")[1];
        if(!originalFilename.split("\\.")[1].equals("mp3")){
            throw new RuntimeException("文件类型不支持");
        }
        TSongEntity sing = new TSongEntity();
        sing.setNameOfSong(attribute[0]);
        sing.setSinger(attribute[1]);
        sing.setFilePath(fileName);


        File f1 = new File("E:\\work\\music\\target\\classes\\static\\mp3\\"+ fileName);
        FileInputStream inputStream = null;
        FileOutputStream outputStream = null;
        try {
            inputStream = (FileInputStream) file.getInputStream();
            outputStream = new FileOutputStream(f1);
            int temp;
            byte[] arr = new byte[1024];
            while((temp = inputStream.read(arr))!=-1){
                outputStream.write(arr);
            }
            tSongMapper.create(sing);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return originalFilename;
    }
}
